package com.ct.commons.aspect.auth;

import com.ct.commons.annotation.HasAdmin;
import com.ct.rbac.enums.RbacResultEnum;
import com.ct.utils.exception.ApiException;
import com.ct.utils.jwt.UserInfo;
import com.ct.utils.threadlocal.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

@Component
@Aspect
@Slf4j
public class SecruityAspect {

    @Pointcut("@annotation(com.ct.commons.annotation.HasAdmin)")
    public void cut() {
    }
//    或者
//    @Pointcut("execution(* com.ct.controller..*Controller.*(..))")
//    public void cut() {
//    }


    @Around("cut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 判断你执行的方法是否存在HasAdmin注解
        HasAdmin methodAnnotation = method.getAnnotation(HasAdmin.class);
        if (methodAnnotation != null) {
            // 如果存在，就开始获取上下文中登录的用户的权限
            UserInfo userInfo = UserThreadLocal.get();
            if (Objects.nonNull(userInfo)) {
                String admin = userInfo.getAdmin();
                // 如果权限不是admin，也就是说是normal就直接抛出异常
                if (StringUtils.isNotEmpty(admin) && !admin.equalsIgnoreCase("admin")) {
                    throw new ApiException(RbacResultEnum.ADMIN_CODE_ERROR);
                }
            }
        }
        Object result = joinPoint.proceed();
        return result;
    }
}


